package com.teapos.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.teapos.service.AdvancePayService;

@SuppressWarnings({"rawtypes", "unchecked"})
@RequestMapping("/advance")
@Controller
public class AdvancePayController extends BaseController {
	
	@Autowired
	private AdvancePayService advancePayService;
	
	@RequestMapping("/index")
	public String index() {
		return "advance/index";
	}
	
	@RequestMapping("/loadProduct")
	public String loadProduct(String id, int unit,  Map map) {
		map.put("info", advancePayService.findProductById(id, unit));
		return "advance/product";
	}
	
	@RequestMapping("/final")
	public String finalStep(HttpServletRequest req) {
		String products = req.getParameter("products");
		String cust = req.getParameter("customer");
		String priceStr = req.getParameter("price");
		List productList = JSON.parseArray(products);
		//System.err.println(productList);
		Map customer = JSON.parseObject(cust);
		Map price = JSON.parseObject(priceStr);
		req.getSession().setAttribute("productList", productList);
		req.getSession().setAttribute("buyback_customer", customer);
		req.getSession().setAttribute("price", price);
		return "advance/final";
	}
	
	@RequestMapping("/pay")
	public String pay() {
		return "advance/pay";
	}
	
	@ResponseBody
	@RequestMapping("/buy")
	public String buy(HttpServletRequest req) {
		Map map = super.getParaMap(req);
		map.put("products", req.getSession().getAttribute("productList"));
		map.put("customer", req.getSession().getAttribute("buyback_customer"));
		map.put("price", req.getSession().getAttribute("price"));
		map.put("user", super.getUser(req));
		try {
			advancePayService.checkAndSaveOrder(map);
			return success("下单成功！！");
		} catch (Exception e) {
			e.printStackTrace();
			return fail("下单失败！！");
		}
	}

}
